/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "framework/common.h"

#include <dirent.h>
#include <sys/types.h>

#include <fstream>
#include <sstream>

namespace air {
namespace link {

std::vector<std::string> SplitMsgName(const std::string& name) {
  std::vector<std::string> name_list;
  std::string item;
  std::stringstream ss(name);
  while (std::getline(ss, item, '.')) {
    name_list.push_back(item);
  }
  return name_list;
}

std::vector<std::string> Common::GetDirFiles(const std::string& conf_path) {
  std::vector<std::string> res;
  DIR* dir = opendir(conf_path.c_str());
  if (dir == nullptr) {
    return res;
  }
  struct dirent* entry = nullptr;
  while (nullptr != (entry = readdir(dir))) {
    if (entry->d_type == DT_REG) {
      res.emplace_back(conf_path + entry->d_name);
    }
  }
  closedir(dir);
  return res;
}

Json::Value Common::LoadJsonFromFile(const std::string& json_file) {
  std::ifstream ifs(json_file);
  if (!ifs.is_open()) {
    return Json::Value::null;
  }
  Json::Value root;
  Json::Reader reader(Json::Features::strictMode());
  if (!reader.parse(ifs, root)) {
    ifs.close();
    return Json::Value::null;
  }
  ifs.close();
  return root;
}

}  // namespace link
}  // namespace air
